package com.fancy.aspect;


import com.fancy.exception.SellAuthorizeException;
import com.fancy.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 登录权限验证
 * Created by FancyFong on 11/9/2017.
 */
@Aspect
@Component
@Slf4j
public class SellAuthorizeAspect {

    @Autowired
    private StringRedisTemplate redicTemplate;

    //切入点 controller.web下的所有方法，排除LoginController里面的方法
    @Pointcut("execution(public * com.fancy.controller.web.*.*(..)) && !execution(public * com.fancy.controller.web.LoginController.*(..))")
    public void verify(){};

    @Before("verify()")
    public void doVerify(){
        ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //查询cookie
        Cookie cookie = CookieUtil.get(request,"token");
        if(cookie==null){
            log.info("【登录校验】Cookic中查不到token");
            throw new SellAuthorizeException();
        }

        //去redis里去查
        System.out.printf("token_"+cookie.getValue());
        String tokenValue = redicTemplate.opsForValue().get("token_"+cookie.getValue());
        if(StringUtils.isEmpty(tokenValue)){
            log.info("【登录校验】redis中查不到token");
            throw new SellAuthorizeException();
        }

    }


}
